import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs/promises';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 确保上传目录存在
const uploadsDir = join(__dirname, '..', 'uploads');
await fs.mkdir(uploadsDir, { recursive: true });

// AI API 配置
const AI_API_CONFIG = {
  stableDiffusion: {
    url: process.env.STABLE_DIFFUSION_API_URL || 'https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image',
    apiKey: process.env.STABLE_DIFFUSION_API_KEY
  },
  dalle: {
    url: 'https://api.openai.com/v1/images/generations',
    apiKey: process.env.OPENAI_API_KEY
  }
};

// 生成头像图片
export const generateAvatarImage = async (settings) => {
  try {
    // 生成描述文本
    const description = generateDescription(settings);
    
    // 尝试调用 AI API 生成图片
    let imageUrl = null;
    let jobId = uuidv4();
    
    try {
      // 优先尝试 Stable Diffusion
      if (AI_API_CONFIG.stableDiffusion.apiKey) {
        imageUrl = await callStableDiffusion(description);
      }
      
      // 如果 Stable Diffusion 失败，尝试 DALL-E
      if (!imageUrl && AI_API_CONFIG.dalle.apiKey) {
        imageUrl = await callDalle(description);
      }
    } catch (error) {
      console.warn('AI API 调用失败，使用模板图片:', error.message);
    }
    
    // 如果 AI 生成成功，保存图片
    if (imageUrl) {
      try {
        const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
        const filename = `${jobId}.png`;
        const filepath = join(uploadsDir, filename);
        
        await fs.writeFile(filepath, response.data);
        
        return {
          imageUrl: `/uploads/${filename}`,
          jobId,
          description,
          settings,
          isTemplate: false
        };
      } catch (error) {
        console.error('保存 AI 生成的图片失败:', error);
      }
    }
    
    // 如果 AI 生成失败，使用模板图片
    const template = await getAvatarTemplate(settings.type, settings.gender);
    
    return {
      imageUrl: template.imageUrl,
      jobId,
      description,
      settings,
      isTemplate: true
    };
    
  } catch (error) {
    console.error('生成头像失败:', error);
    throw new Error('头像生成失败: ' + error.message);
  }
};

// 调用 Stable Diffusion API
const callStableDiffusion = async (description) => {
  try {
    const response = await axios.post(AI_API_CONFIG.stableDiffusion.url, {
      text_prompts: [
        {
          text: description,
          weight: 1
        }
      ],
      cfg_scale: 7,
      height: 1024,
      width: 1024,
      samples: 1,
      steps: 30
    }, {
      headers: {
        'Authorization': `Bearer ${AI_API_CONFIG.stableDiffusion.apiKey}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });
    
    if (response.data.artifacts && response.data.artifacts[0]) {
      return `data:image/png;base64,${response.data.artifacts[0].base64}`;
    }
    
    throw new Error('Stable Diffusion API 返回数据格式错误');
  } catch (error) {
    console.error('Stable Diffusion API 调用失败:', error.message);
    throw error;
  }
};

// 调用 DALL-E API
const callDalle = async (description) => {
  try {
    const response = await axios.post(AI_API_CONFIG.dalle.url, {
      prompt: description,
      n: 1,
      size: '1024x1024',
      response_format: 'url'
    }, {
      headers: {
        'Authorization': `Bearer ${AI_API_CONFIG.dalle.apiKey}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.data.data && response.data.data[0]) {
      return response.data.data[0].url;
    }
    
    throw new Error('DALL-E API 返回数据格式错误');
  } catch (error) {
    console.error('DALL-E API 调用失败:', error.message);
    throw error;
  }
};

// 生成描述文本
const generateDescription = (settings) => {
  const { type, gender, expression, age, customDescription, personality } = settings;
  
  let description = `A professional ${gender} ${type} avatar`;
  
  if (age) {
    description += `, age ${age}`;
  }
  
  if (expression) {
    description += `, ${expression} expression`;
  }
  
  if (personality && personality.length > 0) {
    description += `, ${personality.join(', ')} personality`;
  }
  
  if (customDescription) {
    description += `, ${customDescription}`;
  }
  
  description += ', high quality, professional headshot, clean background';
  
  return description;
};

// 获取预设的形象模板
export const getAvatarTemplates = () => {
  return [
    {
      id: 'engineer-male',
      type: 'engineer',
      gender: 'male',
      name: '工程师-男性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=engineer-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '专业严谨的男性工程师形象'
    },
    {
      id: 'engineer-female',
      type: 'engineer',
      gender: 'female',
      name: '工程师-女性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=engineer-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '专业严谨的女性工程师形象'
    },
    {
      id: 'technician-male',
      type: 'technician',
      gender: 'male',
      name: '技术员-男性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=technician-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '年轻有为的男性技术员形象'
    },
    {
      id: 'technician-female',
      type: 'technician',
      gender: 'female',
      name: '技术员-女性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=technician-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '年轻有为的女性技术员形象'
    },
    {
      id: 'architect-male',
      type: 'architect',
      gender: 'male',
      name: '建筑师-男性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=architect-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '专业自信的男性建筑师形象'
    },
    {
      id: 'architect-female',
      type: 'architect',
      gender: 'female',
      name: '建筑师-女性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=architect-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '专业优雅的女性建筑师形象'
    },
    {
      id: 'consultant-male',
      type: 'consultant',
      gender: 'male',
      name: '顾问-男性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=consultant-male&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '睿智专业的男性顾问形象'
    },
    {
      id: 'consultant-female',
      type: 'consultant',
      gender: 'female',
      name: '顾问-女性',
      imageUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=consultant-female&backgroundColor=b6e3f4&radius=50&style=circle&width=180&height=280',
      description: '睿智专业的女性顾问形象'
    }
  ];
};

// 根据类型和性别获取特定模板
export const getAvatarTemplate = (type, gender) => {
  const templates = getAvatarTemplates();
  return templates.find(t => t.id === `${type}-${gender}`) || templates[0];
};
